package com.ctshk.rpc.hotel.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.XML;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ctshk.common.constant.CurrencyIdCode;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.ApprovalStatus;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.ProductType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.enums.hotel.HotelApiSupplier;
import com.ctshk.common.enums.payment.PayCurrency;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.NumberUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.hotel.APIUtils.GetApiUtils;
import com.ctshk.rpc.hotel.dto.*;
import com.ctshk.rpc.hotel.dto.order.OrderDTO;
import com.ctshk.rpc.hotel.dto.rate.*;
import com.ctshk.rpc.hotel.dto.rooms.HotelRoomsDTO;
import com.ctshk.rpc.hotel.entity.*;
import com.ctshk.rpc.hotel.entity.Hotel;
import com.ctshk.rpc.hotel.entity.HotelFacilities;
import com.ctshk.rpc.hotel.entity.HotelProduct;
import com.ctshk.rpc.hotel.entity.HotelRoomType;
import com.ctshk.rpc.hotel.mapper.*;
import com.ctshk.rpc.hotel.req.GetAllNCNBRoomByCodeReq;
import com.ctshk.rpc.hotel.req.HotelSearchReq;
import com.ctshk.rpc.hotel.req.NCNBHotelCreateOrderReq;
import com.ctshk.rpc.hotel.req.RatePlanSearchReq;
import com.ctshk.rpc.hotel.service.INCNBHotelService;
import com.ctshk.rpc.system.dto.MainDataRowFieldDataDTO;
import com.ctshk.rpc.system.req.MainDataRowFieldDataReq;
import com.ctshk.rpc.system.service.IMainDataTableService;
import com.github.houbb.heaven.util.util.CollectionUtil;
import com.github.houbb.opencc4j.util.ZhConverterUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.xpath.XPathConstants;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@DubboService
@RefreshScope
public class NCNBHotelServiceImpl implements INCNBHotelService {
    @Autowired
    private HotelMapper hotelMapper;
    @Autowired
    private HotelProductMapper hotelProductMapper;
    @Autowired
    private HotelRoomTypeMapper hotelRoomTypeMapper;
    @Autowired
    private HotelFacilitiesMapper hotelFacilitiesMapper;
    @Autowired
    private HotelStaticCityMapper hotelStaticCityMapper;
    @Autowired
    private HotelStaticProvienceMapper hotelStaticProvienceMapper;
    @Autowired
    private HotelStaticCountryMapper hotelStaticCountryMapper;
    @Autowired
    private HotelProductCostMapper hotelProductCostMapper;
    @Autowired
    private HotelProductCostDateMapper hotelProductCostDateMapper;
    @Autowired
    private HotelProductStrategyMapper hotelProductStrategyMapper;
    @Autowired
    private HotelProductStrategyDateMapper hotelProductStrategyDateMapper;
    @Autowired
    private HotelProductChannelOfflineAgentCustomMapper hotelProductChannelOfflineAgentCustomMapper;
    @Autowired
    private HotelProductChannelOfflineSelfCustomMapper hotelProductChannelOfflineSelfCustomMapper;
    @Autowired
    private HotelProductChannelOnlineSelfPlatformMapper hotelProductChannelOnlineSelfPlatformMapper;
    @Autowired
    private HotelProductChannelOnlineThirdPlatformMapper hotelProductChannelOnlineThirdPlatformMapper;
    @Autowired
    private HotelProductIncreaseStrategyRuleMapper hotelProductIncreaseStrategyRuleMapper;
    @Autowired
    private HotelInitializationSettingsMapper hotelInitializationSettingsMapper;

    @DubboReference
    private IMainDataTableService mainDataTableService;

    //删除标识 0：未删除，1：已删除
    private static final Integer NO_DELETE  = 0;
    private static final Integer YES_DELETE  = 1;

    //是否是免费WIFI 1：不是，2：是
    private static final Integer IS_FREE_NO  = 1;
    private static final Integer IS_FREE_YES  = 2;
    //请求数据header类型
    private static final String contextType = "application/x-www-form-urlencoded";
    //龙腾webService接口路径
    private static final String ncnbUrl = "/RESTServer.asmx/GetJsonData";
    //龙腾webService接口路径-获取城市
    private static final String hotelCityUrl = "/StaticInfoQuery.aspx?ActionName=CityQuery&auth=";
    //龙腾webService接口路径-获取酒店集团或者品牌
    private static final String hotelAffiliatedGroupUrl = "/StaticInfoQuery.aspx?ActionName=AffiliatedGroupQuery&auth=";
    private String auth = "RU4wMDAwMDFFMTBBREMzOTQ5QkE1OUFCQkU1NkUwNTdGMjBGODgzRTM2OWI0NjljLTUxYjItNDNjZC05Njc3LTkzNGNhMTdmMjY1MVJVNHdNREF3TURGRk1UQkJSRU16T1RRNVFrRTFPVUZDUWtVMU5rVXdOVGRHTWpCR09EZ3pSVE0yT1dJME5qbGpMVFV4WWpJdE5ETmpaQzA1TmpjM0xUa3pOR05oTVRkbU1qWTFNUT09Cg==";

    // 龙腾捷旅主数据供应商id
    private final static Long SUPPLIER_ID = 64416510877106176L;
    private final static String SUPPLIER_NAME = "龍騰捷旅";

    @Value("${thirdparty.ncnb.appid}")
    private String appId;
    @Value("${thirdparty.ncnb.username}")
    private String username;
    @Value("${thirdparty.ncnb.password}")
    private String password;
    @Value("${thirdparty.ncnb.security-key}")
    private String securityKey;
    @Value("${thirdparty.ncnb.domain}")
    private String domain;

    /**
     * 初始化酒店信息
     */
    @Override
    public Result initialize() {
        log.info("执行[龙腾捷旅]初始化酒店信息");
        // 获取所有酒店区域列表
        ThreadUtil.execAsync(() -> {
            log.info("[龙腾捷旅]初始化酒店信息异步线程-start");
            TimeInterval timer = DateUtil.timer();
            List<CNHotelAreaDTO> cnHotelAreaDTOS = queryHotelCityList();
            TokenUser tokenUser = new TokenUser();
            tokenUser.setId(1344284712813568L);
            tokenUser.setUsername("管理员");
            tokenUser.setEmployeeNumber("0000001");
            log.info("[龙腾捷旅]酒店城市共有[{}]个", cnHotelAreaDTOS.size());
            // 拉取酒店品牌数据
            List<AffiliatedGroup> affiliatedGroups = queryAffiliatedGroup();
            log.info("[龙腾捷旅]酒店品牌共有[{}]个", affiliatedGroups.size());
            List<String> countryIds = Arrays.asList("0001","0002","0003","0004");
            // 获取api初始化设置(服务费和退改费)
            HotelInitializationSettings hotelInitializationSettings = hotelInitializationSettingsMapper.selectOne(Wrappers.<HotelInitializationSettings>lambdaQuery()
                    .eq(HotelInitializationSettings::getSupplierId, SUPPLIER_ID)
                    .eq(HotelInitializationSettings::getIsDeleted, NO_DELETE));
            if (null == hotelInitializationSettings) {
                hotelInitializationSettings = new HotelInitializationSettings();
            }
            HotelSearchReq req = null;
            for (CNHotelAreaDTO cnHotelAreaDTO : cnHotelAreaDTOS) {
                log.info("[龙腾捷旅]初始化酒店信息-国家[id:{},名称:{}],省份[id:{},名称{}],城市[id:{},名称:{}]", cnHotelAreaDTO.getCountryId(), cnHotelAreaDTO.getCountryName(), cnHotelAreaDTO.getProvinceId(), cnHotelAreaDTO.getProvinceName(), cnHotelAreaDTO.getCityId(), cnHotelAreaDTO.getCityName());
                // 如果cityId为空则不进行查询插入(临时只查询0001-中国大陆,0002-中国香港,0003-中国台湾,0004-中国澳门。这4个区域酒店)
                if (StringUtils.isBlank(cnHotelAreaDTO.getCityId()) || !countryIds.contains(cnHotelAreaDTO.getCountryId())) {
                    log.info("[龙腾捷旅]当前酒店城市不拉取-国家[id:{},名称:{}],省份[id:{},名称{}],城市[id:{},名称:{}]", cnHotelAreaDTO.getCountryId(), cnHotelAreaDTO.getCountryName(), cnHotelAreaDTO.getProvinceId(), cnHotelAreaDTO.getProvinceName(), cnHotelAreaDTO.getCityId(), cnHotelAreaDTO.getCityName());
                    continue;
                }
                req = new HotelSearchReq();
                req.setCountryId(cnHotelAreaDTO.getCountryId());
                req.setProvinceId(cnHotelAreaDTO.getProvinceId());
                req.setCityId(cnHotelAreaDTO.getCityId());
                Result result = saveAPINCNBHotel(req, affiliatedGroups, tokenUser, hotelInitializationSettings.getPackStatus(), hotelInitializationSettings.getServiceCharge(), new BigDecimal(hotelInitializationSettings.getRefundServiceCharge()), hotelInitializationSettings.getServiceChargeType(), hotelInitializationSettings.getRefundServiceChargeType());
                log.info("[龙腾捷旅]初始化酒店信息-获取结果[{}]", result.getMsg());
            }
            log.info("[龙腾捷旅]初始化酒店信息异步线程-end,一共花费[{}]分钟", timer.intervalMinute());
        });
        return Result.success();
    }

    @Override
    public Result saveAPINCNBHotel(HotelSearchReq req, List<AffiliatedGroup> affiliatedGroups,TokenUser tokenUser, Integer allowPackage, BigDecimal reserveCharge, BigDecimal refundCharge, Integer reserveChargeType, Integer refundChargeType) {
        log.info("进入龙腾[HotelSearch]查询接口 req[{}]", req);
        String countryId = "";
        if (StringUtils.isNotBlank(req.getCountryId())){
            countryId = req.getCountryId();
        }
        String provinceId = "";
        if (StringUtils.isNotBlank(req.getProvinceId())){
            provinceId = req.getProvinceId();
        }
        String cityId = "";
        if (StringUtils.isNotBlank(req.getCityId())){
            cityId = req.getCityId();
        }
        String hotelId = "";
        if (StringUtils.isNotBlank(req.getHotelId())){
            hotelId = req.getHotelId();
        }
        String lang = "";
        if (StringUtils.isNotBlank(req.getLang())){
            lang = req.getLang();
        }
        String pwd = SecureUtil.md5(password).toUpperCase();
        String params = "xmlRequest=<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<CNRequest>\n" +
                "  <!--用户信息-->\n" +
                "  <ActionName>HotelSearch</ActionName>\n" +
                "  <IdentityInfo>\n" +
                "    <AppId>" + appId + "</AppId>\n" +
                "    <SecurityKey>" + securityKey + "</SecurityKey>\n" +
                "    <UserName>" + username + "</UserName>\n" +
                "    <PassWord>" + pwd + "</PassWord>\n" +
                "    <Signature>" + Base64.encode(username+pwd+securityKey) + "</Signature>\n" +
                "  </IdentityInfo>\n" +
                "  <ScrollingInfo>\n" +
                "    <DisplayReq>30</DisplayReq>\n" +
                "    <PageItems>10</PageItems>\n" +
                "    <PageNo>1</PageNo>\n" +
                "  </ScrollingInfo>\n" +
                "  <!--查询条件-->\n" +
                "  <SearchConditions>\n" +
                "    <CountryId>"+countryId+"</CountryId>\n" +
                "    <ProvinceId>"+provinceId+"</ProvinceId>\n" +
                "    <CityId>\n" +cityId+
                "    </CityId>\n" +
                "    <HotelId>\n" +hotelId+
                "    </HotelId>\n" +
                "    <Lang>\n" +lang+
                "    </Lang>\n" +
                "  </SearchConditions>\n" +
                "</CNRequest>";
        //请求数据
        String returnStr = HttpUtil.post(domain + ncnbUrl, params);
        log.info("酒店returnStr之前[{}]",returnStr);
        returnStr = returnStr.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>","");
        returnStr = returnStr.replace("<string xmlns=\"http://tempuri.org/\">","");
        returnStr = returnStr.replace("</string>","");
        log.info("酒店returnStr之后[{}]",returnStr);
        try {
            JSONObject object = XML.toJSONObject(returnStr);
            log.info("酒店object[{}]",object);
            //结果转化为JSON，然后转化为对象，方便处理
            //  List<NCNBHotelsDTO> NCNBHotelsDTO = (List<NCNBHotelsDTO>) JSON.parseArray(String.valueOf(returnStr), NCNBHotelsDTO.class);
            JSONObject j = new JSONObject(returnStr);
            log.info("酒店jsonObject[{}]",j);
            int code = j.getJSONObject("CNResponse").getJSONObject("MessageInfo").getInt("Code");
            if (code != 30000) {
                // 请求失败
                log.info("API【龙腾捷旅】-方法【HotelSearch】调用失败,错误信息:[{}]", j.getJSONObject("CNResponse").getJSONObject("MessageInfo").get("Description"));
                return Result.failed(SystemError.HOTEL_API_10089);
                // throw new BusinessException(SystemError.HOTEL_API_10089);
            }
            JSONArray hotelDate = j.getJSONObject("CNResponse").getJSONObject("Data").getJSONObject("Hotels").getJSONArray("Hotel");
            List<NCNBHotelsDTO> ntHotelList = JSON.parseArray(String.valueOf(hotelDate), NCNBHotelsDTO.class);
            if(ntHotelList!=null){
                log.info("[HotelSearch]获取到酒店信息,进行插入或者更新操作");
                for (int i = 0; i <ntHotelList.size() ; i++) {
                    NCNBHotelsDTO ncnbHotelsDTOObj = ntHotelList.get(i);
                    // 获取到酒店后先校验当前酒店是否已存在
                    Hotel hotel = hotelMapper.selectOne(Wrappers.<Hotel>lambdaQuery()
                            .eq(Hotel::getHotelCode, ncnbHotelsDTOObj.getHotelId())
                            .eq(Hotel::getIsDeleted, 0));
                    boolean isExistHotel = false;
                    if (hotel == null) {
                        hotel = new Hotel();
                        isExistHotel = false;
                    } else {
                        isExistHotel = true;
                    }
                    // 遍历获取酒店品牌数据
                    String brandName = ncnbHotelsDTOObj.getHotelName();
                    if (CollUtil.isNotEmpty(affiliatedGroups)) {
                        for (AffiliatedGroup affiliatedGroup : affiliatedGroups) {
                            if (StringUtils.equals(ncnbHotelsDTOObj.getReserve3().getAffiliatedGroupId(), affiliatedGroup.getAffiliatedGroupId())) {
                                brandName = affiliatedGroup.getAffiliatedGroupName();
                                break;
                            }
                        }
                    }
                    long id = SnowflakeIdWorker.nextId();
                    LocalDateTime now = LocalDateTime.now();
                    hotel.setSourceType(ProductType.API_PRODUCT.getCode());//酒店来源
                    hotel.setHotelCode(ncnbHotelsDTOObj.getHotelId());//酒店ID
                    hotel.setBrandName(brandName);//酒店品牌
                    //区域ID为主数据ID
                    hotel.setCountryId(null);
                    hotel.setCountryName(ZhConverterUtil.toTraditional(ncnbHotelsDTOObj.getCountryName()));
                    hotel.setProvinceId(null);
                    hotel.setProvinceName(ZhConverterUtil.toTraditional(ncnbHotelsDTOObj.getProvinceName()));
                    hotel.setCityId(null);
                    hotel.setCityName(ZhConverterUtil.toTraditional(ncnbHotelsDTOObj.getCityName()));
                    hotel.setAreaId(null);
                    hotel.setAreaName(null);
                    hotel.setEnName(null);//需要再次调用以英文参数查询的酒店接口
                    hotel.setName(ZhConverterUtil.toTraditional(ncnbHotelsDTOObj.getHotelName()));
                    hotel.setStarLevel(getStarLevelFunc(ncnbHotelsDTOObj.getStar()));
                    hotel.setTelephone(ncnbHotelsDTOObj.getReserve2());
                    hotel.setLocation(ZhConverterUtil.toTraditional(ncnbHotelsDTOObj.getAddress()));
                    hotel.setLatitude(ncnbHotelsDTOObj.getLat());
                    hotel.setLongitude(ncnbHotelsDTOObj.getLon());
                    hotel.setPostalCode(ncnbHotelsDTOObj.getPostCode());
                    hotel.setEmail(ncnbHotelsDTOObj.getEmail());
                    hotel.setOpeningTime(ncnbHotelsDTOObj.getStartBusinessDate());
                    hotel.setFinalRenovationTime(ncnbHotelsDTOObj.getRepairdate());
                    hotel.setHotelContent(ZhConverterUtil.toTraditional(ncnbHotelsDTOObj.getIntro().replace("&lt;![CDATA[","").replace("]]&gt;","")));
                    hotel.setCustomerGuide(ZhConverterUtil.toTraditional(ncnbHotelsDTOObj.getGuide()));
                    hotel.setIsDeleted(NO_DELETE);
                    hotel.setApiSupplier(HotelApiSupplier.NCNB.name());
                    //商圈可能很多个，但是只保存一个。
                    if(ncnbHotelsDTOObj.getLandmarks()!=null){
                        if(CollectionUtil.isNotEmpty(ncnbHotelsDTOObj.getLandmarks().getLandMark())){
                            if(ncnbHotelsDTOObj.getLandmarks().getLandMark().get(0).getDistance()!=null){
                                hotel.setLocToDistrictDistance(ZhConverterUtil.toTraditional("距離" + ncnbHotelsDTOObj.getLandmarks().getLandMark().get(0).getLandName() + ncnbHotelsDTOObj.getLandmarks().getLandMark().get(0).getDistance() + "公里"));//距离商圈距离
                            }
                            if(ncnbHotelsDTOObj.getLandmarks().getLandMark().get(0).getLandName()!=null){
                                hotel.setBusinessDistrictName(ZhConverterUtil.toTraditional(ncnbHotelsDTOObj.getLandmarks().getLandMark().get(0).getLandName()));//距离商圈距离
                            }
                            if(ncnbHotelsDTOObj.getLandmarks().getLandMark().get(0).getLandid()!=null){
                                hotel.setBusinessDistrictId(ncnbHotelsDTOObj.getLandmarks().getLandMark().get(0).getLandid());//距离商圈距离
                            }
                        }
                    }
                    List<Image> imageList = ncnbHotelsDTOObj.getReserve1().getImages().getImage();
                    JSONArray jsonArray = new JSONArray();
                    String cover = null;
                    if(imageList!=null){
                        for (int k = 0; k < imageList.size() ; k++) {
                            if (k == 0) {
                                cover = imageList.get(k).getImageUrl();
                            }
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.putOpt("url", imageList.get(k).getImageUrl());
                            jsonArray.add(jsonObject);
                        }
                    }
                    hotel.setCoverMap(cover);
                    hotel.setShowPhotoJson(jsonArray.toString());
                    if (isExistHotel) {
                        log.info("当前酒店hotelCode[{}]已存在,更新酒店资源", hotel.getHotelCode());
                        id = hotel.getId();
                        hotel.setModifiedId(tokenUser.getId());
                        hotel.setGmtModified(now);
                        hotelMapper.updateById(hotel);
                    } else {
                        log.info("当前酒店hotelCode[{}]不存在,写入酒店资源", hotel.getHotelCode());
                        hotel.setId(id);
                        hotel.setCreateId(tokenUser.getId());
                        hotel.setGmtCreate(now);
                        hotel.setGmtModified(now);
                        hotelMapper.insert(hotel);
                    }
                    //酒店设施储存
                    Reserve3 reserve3 = ncnbHotelsDTOObj.getReserve3();
                    if(null != reserve3){
                        List<Service> serviceList = reserve3.getServices().getService();
                        Services services = reserve3.getServices();
                        if(null != services){
                            // 删除旧的酒店设施
                            hotelFacilitiesMapper.delete(Wrappers.<HotelFacilities>lambdaQuery().eq(HotelFacilities::getHotelId, id));
                            List<Service> service1 = services.getService();
                            if(CollectionUtils.isNotEmpty(serviceList)){
                                for (int k = 0; k <serviceList.size(); k++) {
                                    Service service = serviceList.get(k);
                                    HotelFacilities hotelFacilities = new HotelFacilities();
                                    hotelFacilities.setId(SnowflakeIdWorker.nextId());
                                    hotelFacilities.setHotelId(id);
                                    hotelFacilities.setFacilitiesId(null);
                                    hotelFacilities.setCreateId(tokenUser.getId());
                                    hotelFacilities.setFacilitiesName(service.getServiceName());
                                    hotelFacilities.setGmtCreate(now);
                                    hotelFacilities.setGmtModified(now);
                                    hotelFacilities.setIsDeleted(NO_DELETE);
                                    // 保存酒店设施
                                    hotelFacilitiesMapper.insert(hotelFacilities);
                                }
                            }
                        }
                    }
                    //酒店房型保存
                    GetAllNCNBRoomByCodeReq getAllNCNBRoomByCodeReq = new GetAllNCNBRoomByCodeReq();
                    getAllNCNBRoomByCodeReq.setCountryId(countryId);
                    getAllNCNBRoomByCodeReq.setProvinceId(provinceId);
                    getAllNCNBRoomByCodeReq.setHotelId(hotel.getHotelCode());
                    getAllNCNBRoomByCodeReq.setId(id);
                    saveAPINCNBHotelRoom(getAllNCNBRoomByCodeReq, tokenUser, allowPackage, reserveCharge, refundCharge, reserveChargeType, refundChargeType);
                }
            }
        } catch (Exception e) {
            log.error("API【龙腾捷旅】-方法【HotelSearch】解析失败,错误信息:[{}]", e.getMessage());
            return Result.failed(SystemError.HOTEL_API_10089);
        }
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveAPINCNBHotelRoom(GetAllNCNBRoomByCodeReq getAllNCNBRoomByCodeReq,TokenUser tokenUser, Integer allowPackage, BigDecimal reserveCharge, BigDecimal refundCharge, Integer reserveChargeType, Integer refundChargeType) {
        log.info("进入[RoomSearch]获取酒店房间信息,req[{}]", getAllNCNBRoomByCodeReq);
        LocalDateTime now = LocalDateTime.now();
        String pwd = SecureUtil.md5(password).toUpperCase();
        String param = "xmlRequest=<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<CNRequest>\n" +
                "  <!--用户信息-->\n" +
                "  <ActionName>RoomSearch</ActionName>\n" +
                "  <IdentityInfo>\n" +
                "    <AppId>" + appId + "</AppId>\n" +
                "    <SecurityKey>" + securityKey + "</SecurityKey>\n" +
                "    <UserName>" + username + "</UserName>\n" +
                "    <PassWord>" + pwd + "</PassWord>\n" +
                "    <Signature>" + Base64.encode(username+pwd+securityKey) + "</Signature>\n" +
                "  </IdentityInfo>\n" +
                "  <ScrollingInfo>\n" +
                "    <DisplayReq>30</DisplayReq>\n" +
                "    <PageItems>10</PageItems>\n" +
                "    <PageNo>1</PageNo>\n" +
                "  </ScrollingInfo>\n" +
                "  <!--查询条件-->\n" +
                "  <SearchConditions>\n" +
                "    <CountryId>"+getAllNCNBRoomByCodeReq.getCountryId()+"</CountryId>\n" +
                "    <ProvinceId>"+getAllNCNBRoomByCodeReq.getProvinceId()+"</ProvinceId>\n" +
                "    <CityId>\n" +
                "    </CityId>\n" +
                "    <HotelId>"+getAllNCNBRoomByCodeReq.getHotelId()+"</HotelId>\n" +
                "    <RoomId>\n" +
                "    </RoomId>\n" +
                "    <Lang>\n" +
                "    </Lang>\n" +
                "  </SearchConditions>\n" +
                "</CNRequest>";
        String returnStr = HttpUtil.post(domain + ncnbUrl, param);
        log.info("房型returnStr[{}]", returnStr);
        try {
            JSONObject object = XML.toJSONObject(returnStr);
            log.info("房型object[{}]",object);
            JSONObject jsonObject = JSONUtil.parseFromXml(returnStr).getJSONObject("string").getJSONObject("content").getJSONObject("CNResponse");
            log.info("房型jsonObject[{}]",jsonObject);
            HotelRoomsDTO hotelRoomsDTO = JSONUtil.toBean(jsonObject, HotelRoomsDTO.class);
            if(null != hotelRoomsDTO.getData()){
                com.ctshk.rpc.hotel.dto.rooms.Hotels hotels = hotelRoomsDTO.getData().getHotels();
                if(null != hotels){
                    List<com.ctshk.rpc.hotel.dto.rooms.Hotel> hotelList = hotels.getHotel();
                    if(CollectionUtils.isNotEmpty(hotelList)){
                        for (com.ctshk.rpc.hotel.dto.rooms.Hotel hotel:hotelList ) {
                            String hotelId = hotel.getHotelId();
                            String hotelName = hotel.getHotelName();
                            if(CollectionUtils.isNotEmpty(hotel.getRooms().getRoom())){
                                log.info("[RoomSearch]获取到酒店房间信息");
                                for (com.ctshk.rpc.hotel.dto.rooms.Room room:hotel.getRooms().getRoom()) {
                                    String outRoomId = room.getRoomId();
                                    HotelRoomType hotelRoomType = new HotelRoomType();
                                    long roomId = SnowflakeIdWorker.nextId();
                                    // 获取当前房间是否已经存在
                                    HotelRoomType roomType = hotelRoomTypeMapper.selectOne(Wrappers.<HotelRoomType>lambdaQuery()
                                            .eq(HotelRoomType::getProductCode, outRoomId)
                                            .eq(HotelRoomType::getIsDeleted, 0));
                                    if (null != roomType) {
                                        hotelRoomType = roomType;
                                    }
                                    if(null != getAllNCNBRoomByCodeReq.getId()){
                                        hotelRoomType.setHotelId(getAllNCNBRoomByCodeReq.getId());
                                    }
                                    hotelRoomType.setName(room.getRoomName());
                                    hotelRoomType.setEnName(null);
                                    if(StringUtils.isNotBlank(room.getMaxAdult())){
                                        hotelRoomType.setMaxAdult(Integer.parseInt(room.getMaxAdult()));
                                    }
                                    if(StringUtils.isNotBlank(room.getMaxChild())) {
                                        hotelRoomType.setMaxChildren(Integer.parseInt(room.getMaxChild()));
                                    }
                                    if(StringUtils.isNotBlank(room.getRoomAcount())) {
                                        hotelRoomType.setRoomNum(Integer.parseInt(room.getRoomAcount()));
                                    }
                                    if(StringUtils.isNotBlank(room.getAcreage())) {
                                        //hotelRoomType.setAreaMeasure(Double.parseDouble(room.getAcreage()));
                                    }
                                    hotelRoomType.setRoomFloors(room.getFloor());
                                    if(StringUtils.isNotBlank(room.getRoomTypeId())) {
                                        hotelRoomType.setRoomTypeId(Long.valueOf(room.getRoomTypeId()));
                                    }
                                    hotelRoomType.setRoomFloors(room.getFloor());
                                    hotelRoomType.setRoomType(room.getRoomType());
                                    hotelRoomType.setCanAddBed(null != room.getAllowAddBed() && room.getAllowAddBed().equals("1")?1:0);
                                    hotelRoomType.setHasWindow(null != room.getHasWindow() && room.getHasWindow().equals("1")?1:0);
                                    hotelRoomType.setAllowSmoke(null != room.getAllowSmoke() && room.getAllowSmoke().equals("1")?1:0);
                                    hotelRoomType.setIsFreeNet(null != room.getHasNet() && room.getHasNet().equals("1")?1:0);
                                    hotelRoomType.setNetTypeId(null);
                                    hotelRoomType.setNetType(null);
                                    if(StringUtils.isNotBlank(room.getBedTypeId())) {
                                        hotelRoomType.setBedTypeId(Long.parseLong(room.getBedTypeId()));
                                    }
                                    hotelRoomType.setBedType(room.getBedType());
                                    if(StringUtils.isNotBlank(room.getAllowAddBedNum())) {
                                        hotelRoomType.setCanAddBed(Integer.parseInt(room.getAllowAddBedNum()));
                                    }
                                    hotelRoomType.setRoomIntroduction(room.getIntro());
                                    hotelRoomType.setProductCode(room.getRoomId());
                                    //费用说明无字段
                                    //方型设施没有
                                    hotelRoomType.setPhotoJson(room.getImages());
                                    hotelRoomType.setGmtModified(now);
                                    hotelRoomType.setModifiedId(tokenUser.getId());

                                    if (null == roomType) {
                                        hotelRoomType.setId(roomId);
                                        hotelRoomType.setGmtCreate(now);
                                        hotelRoomType.setCreateId(tokenUser.getId());
                                        hotelRoomType.setIsDeleted(IsDeletedCode.NO.getCode());
                                        hotelRoomTypeMapper.insert(hotelRoomType);
                                    } else {
                                        hotelRoomType.setId(roomType.getId());
                                        hotelRoomTypeMapper.updateById(hotelRoomType);
                                    }

                                    HotelProduct hotelProduct = new HotelProduct();
                                    // 获取当前房间的产品是否存在
                                    HotelProduct product = hotelProductMapper.selectOne(Wrappers.<HotelProduct>lambdaQuery()
                                            .eq(HotelProduct::getProductCode, outRoomId)
                                            .eq(HotelProduct::getIsDeleted, 0));
                                    if (null != product) {
                                        hotelProduct = product;
                                    }
                                    Long hotelProductId = SnowflakeIdWorker.nextId();
                                    hotelProduct.setSourceType(ProductType.API_PRODUCT.getCode());
                                    //本地酒店ID
                                    if(null != getAllNCNBRoomByCodeReq.getId()){
                                        hotelProduct.setHotelId(getAllNCNBRoomByCodeReq.getId());
                                    }
                                    //本地房型ID
                                    hotelProduct.setSource(ProductType.API_PRODUCT.getCode());
                                    hotelProduct.setRoomId(roomId);
                                    hotelProduct.setName(room.getRoomName());
                                    //无含早信息
                                    //无供应商ID及名称信息
                                    //负责人为当前用户
                                    hotelProduct.setChargeId(tokenUser.getId());
                                    hotelProduct.setChargeUser(tokenUser.getUsername());
                                    //无适用人群ID及信息
                                    hotelProduct.setGmtModified(now);
                                    hotelProduct.setModifiedId(tokenUser.getId());
                                    hotelProduct.setProductCode(room.getRoomId());

                                    if (null == product) {
                                        hotelProduct.setId(hotelProductId);
                                        hotelProduct.setGmtCreate(now);
                                        hotelProduct.setCreateId(tokenUser.getId());
                                        hotelProduct.setIsDeleted(IsDeletedCode.NO.getCode());
                                        hotelProduct.setProductNumber(NumberUtil.generatorHotelProductNumber(tokenUser.getEmployeeNumber()));
                                        hotelProduct.setReserveCharge(reserveCharge);
                                        hotelProduct.setReserveChargeType(reserveChargeType);
                                        hotelProduct.setRefundCharge(refundCharge);
                                        hotelProduct.setRefundChargeType(refundChargeType);
                                        hotelProduct.setAllowPackage(allowPackage);
                                        // api产品默认上架
                                        hotelProduct.setOnShelfStatus(1);
                                        // api产品默认售卖
                                        hotelProduct.setSaleStatus(1);
                                        // api产品默认审核通过
                                        hotelProduct.setApprovalStatus(ApprovalStatus.REVIEW_YES.getCode());
                                        // 默认供应商
                                        hotelProduct.setSupplierId(SUPPLIER_ID);
                                        hotelProduct.setSupplierName(SUPPLIER_NAME);
                                        hotelProductMapper.insert(hotelProduct);
                                    } else {
                                        hotelProduct.setId(product.getId());
                                        hotelProductMapper.updateById(hotelProduct);
                                    }

                                    /**
                                     * 设置成本价-180天内的 start
                                     */
                                    RatePlanSearchReq ratePlanSearchReq = new RatePlanSearchReq();
                                    // CountryId, ProvinceId, CityId 同时传或者只传 HotelId,两者必须具备其一
                                    // ratePlanSearchReq.setCountryId(getAllNCNBRoomByCodeReq.getCountryId());
                                    // ratePlanSearchReq.setProvinceId(getAllNCNBRoomByCodeReq.getProvinceId());
                                    // ratePlanSearchReq.setCityId(getAllNCNBRoomByCodeReq.getCityId());

                                    // 获取3月内每天的价格,90天
                                    LocalDate checkIn = LocalDate.now();
                                    HotelProductCost hotelProductCost = null;
                                    HotelProductStrategy hotelProductStrategy = null;
                                    HotelProductIncreaseStrategyRule offlineSelfRule = null;
                                    HotelProductIncreaseStrategyRule offlineAgentRule = null;
                                    HotelProductStrategyDate strategyDate = null;
                                    // 一次查询10天,一共查询9次=90天
                                    for (int i = 0; i < 9; i++) {
                                        int checkOutIdx = i + 1 * 10;
                                        ratePlanSearchReq.setHotelId(hotelId);
                                        ratePlanSearchReq.setRoomId(outRoomId);
                                        ratePlanSearchReq.setCurrency(PayCurrency.HKD.getCode());
                                        ratePlanSearchReq.setCheckIn(checkIn.plusDays(checkOutIdx - 10).toString());
                                        ratePlanSearchReq.setCheckOut(checkIn.plusDays(checkOutIdx).toString());
                                        List<RatePlanSearchDTO> ratePlanSearchDTOS = queryRatePlanSearch(ratePlanSearchReq);

                                        // 获取当前房间产品的成本是否存在
                                        List<HotelProductCost> productCosts = hotelProductCostMapper.selectList(Wrappers.<HotelProductCost>lambdaQuery()
                                                .eq(HotelProductCost::getHotelProductId, hotelProduct.getId()));
                                        for (HotelProductCost productCost : productCosts) {
                                            // 删除当前成本
                                            hotelProductCostMapper.deleteById(productCost.getId());
                                            // 删除已存在成本日期
                                            hotelProductCostDateMapper.delete(Wrappers.<HotelProductCostDate>lambdaQuery().eq(HotelProductCostDate::getCostId, productCost.getId()));
                                        }

                                        // 获取当前房间产品的加幅是否存在
                                        List<HotelProductStrategy> productStrategies = hotelProductStrategyMapper.selectList(Wrappers.<HotelProductStrategy>lambdaQuery()
                                                .eq(HotelProductStrategy::getHotelProductId, hotelProduct.getId()));
                                        for (HotelProductStrategy productStrategie : productStrategies) {
                                            // 删除当前加幅
                                            hotelProductStrategyMapper.deleteById(productStrategie.getId());
                                            // 删除已存在加幅日期
                                            hotelProductStrategyDateMapper.delete(Wrappers.<HotelProductStrategyDate>lambdaQuery().eq(HotelProductStrategyDate::getIncreaseStrategyId, productStrategie.getId()));
                                            // 删除已存在加幅策略规则
                                            hotelProductIncreaseStrategyRuleMapper.delete(Wrappers.<HotelProductIncreaseStrategyRule>lambdaQuery().eq(HotelProductIncreaseStrategyRule::getIncreaseStrategyId, productStrategie.getId()));
                                            // 删除已存在线上官方自营渠道
                                            hotelProductChannelOnlineSelfPlatformMapper.delete(Wrappers.<HotelProductChannelOnlineSelfPlatform>lambdaQuery().eq(HotelProductChannelOnlineSelfPlatform::getIncreaseStrategyId, productStrategie.getId()));
                                            // 删除已存在线上第三方渠道
                                            hotelProductChannelOnlineThirdPlatformMapper.delete(Wrappers.<HotelProductChannelOnlineThirdPlatform>lambdaQuery().eq(HotelProductChannelOnlineThirdPlatform::getIncreaseStrategyId, productStrategie.getId()));
                                        }
                                        for (RatePlanSearchDTO ratePlanSearchDTO : ratePlanSearchDTOS) {
                                            if(ratePlanSearchDTO.getHotelId().equals(hotelId) && ratePlanSearchDTO.getRoomId().equals(outRoomId)){
                                                hotelProductCost = new HotelProductCost();
                                                long costId = SnowflakeIdWorker.nextId();
                                                hotelProductCost.setId(costId);
                                                hotelProductCost.setHotelProductId(hotelProductId);
                                                hotelProductCost.setCostName("默認成本");
                                                hotelProductCost.setStock(Integer.parseInt(ratePlanSearchDTO.getRatePlanCount()));
                                                //主数据币种ID
                                                hotelProductCost.setCurrencyId(CurrencyIdCode.HKD.getCode());
                                                hotelProductCost.setCurrencyName(PayCurrency.HKD.getName());
                                                hotelProductCost.setExchangeRate(new BigDecimal(1));
                                                hotelProductCost.setPrice(new BigDecimal(ratePlanSearchDTO.getPrice()));
                                                hotelProductCost.setRatePlanId(ratePlanSearchDTO.getRatePlanId());
                                                hotelProductCostMapper.insert(hotelProductCost);
                                                HotelProductCostDate hotelProductCostDate = new HotelProductCostDate();
                                                hotelProductCostDate.setId(SnowflakeIdWorker.nextId());
                                                hotelProductCostDate.setCostId(costId);
                                                hotelProductCostDate.setDateBegin(com.ctshk.common.utils.DateUtil.toLocalDate(DateUtil.toLocalDateTime(ratePlanSearchDTO.getDate())));
                                                hotelProductCostDate.setDateEnd(com.ctshk.common.utils.DateUtil.toLocalDate(DateUtil.toLocalDateTime(ratePlanSearchDTO.getDate()).plusDays(1)));
                                                hotelProductCostDateMapper.insert(hotelProductCostDate);

                                                Long strategyId = SnowflakeIdWorker.nextId();

                                                /**
                                                 * 设置线下自营渠道加幅策略规则
                                                 */
                                                offlineSelfRule = new HotelProductIncreaseStrategyRule();
                                                long offlineSelfRuleId = SnowflakeIdWorker.nextId();
                                                offlineSelfRule.setId(offlineSelfRuleId);
                                                offlineSelfRule.setIncreaseStrategyId(strategyId);
                                                // 加幅类型默认数值加0元
                                                offlineSelfRule.setPriceType(1);
                                                offlineSelfRule.setPrice(BigDecimal.ZERO);
                                                // 可售类型默认不限制可售数
                                                offlineSelfRule.setSaleableType(1);
                                                hotelProductIncreaseStrategyRuleMapper.insert(offlineSelfRule);

                                                /**
                                                 * 设置线下代理商渠道加幅策略规则
                                                 */
                                                offlineAgentRule = new HotelProductIncreaseStrategyRule();
                                                long offlineAgentRuleId = SnowflakeIdWorker.nextId();
                                                offlineAgentRule.setId(offlineAgentRuleId);
                                                offlineAgentRule.setIncreaseStrategyId(strategyId);
                                                // 加幅类型默认数值加0元
                                                offlineAgentRule.setPriceType(1);
                                                offlineAgentRule.setPrice(BigDecimal.ZERO);
                                                // 可售类型默认不限制可售数
                                                offlineAgentRule.setSaleableType(1);
                                                hotelProductIncreaseStrategyRuleMapper.insert(offlineAgentRule);

                                                /**
                                                 * 设置线上所有官方平台加幅策略规则
                                                 * 先查询所有线上官方平台
                                                 */
                                                MainDataRowFieldDataReq selfReq = new MainDataRowFieldDataReq();
                                                selfReq.setFid(1364862712611524609L);
                                                selfReq.setTid(1364862500824338434L);
                                                List<MainDataRowFieldDataDTO> selfDTOS = mainDataTableService.queryDataFieldLikeName(selfReq);
                                                Optional.ofNullable(selfDTOS).orElse(new ArrayList<>()).forEach(dto -> {
                                                    // 新增官方平台加幅策略规则
                                                    long customId = SnowflakeIdWorker.nextId();
                                                    HotelProductChannelOnlineSelfPlatform channelOnlineSelfPlatform = new HotelProductChannelOnlineSelfPlatform();
                                                    channelOnlineSelfPlatform.setId(customId);
                                                    channelOnlineSelfPlatform.setIncreaseStrategyId(strategyId);
                                                    channelOnlineSelfPlatform.setChannelId(dto.getId());
                                                    channelOnlineSelfPlatform.setChannelName(dto.getFieldValue());
                                                    channelOnlineSelfPlatform.setCreateId(tokenUser.getId());
                                                    channelOnlineSelfPlatform.setModifiedId(tokenUser.getId());
                                                    channelOnlineSelfPlatform.setIsDeleted(0);
                                                    channelOnlineSelfPlatform.setGmtCreate(now);
                                                    channelOnlineSelfPlatform.setGmtModified(now);
                                                    hotelProductChannelOnlineSelfPlatformMapper.insert(channelOnlineSelfPlatform);
                                                    // 官方平台加幅策略规则
                                                    HotelProductIncreaseStrategyRule selfRule = new HotelProductIncreaseStrategyRule();
                                                    selfRule.setId(SnowflakeIdWorker.nextId());
                                                    selfRule.setIncreaseStrategyId(strategyId);
                                                    // 加幅类型默认数值加0元
                                                    selfRule.setPriceType(1);
                                                    selfRule.setPrice(BigDecimal.ZERO);
                                                    // 可售类型默认不限制可售数
                                                    selfRule.setSaleableType(1);
                                                    selfRule.setCustomId(customId);
                                                    hotelProductIncreaseStrategyRuleMapper.insert(selfRule);
                                                });

                                                /**
                                                 * 设置线上所有第三方平台加幅策略规则
                                                 * 先查询所有线上第三方平台
                                                 */
                                                MainDataRowFieldDataReq agentReq = new MainDataRowFieldDataReq();
                                                agentReq.setFid(1356434757837279233L);
                                                agentReq.setTid(1356434342349524993L);
                                                List<MainDataRowFieldDataDTO> agentDTOS = mainDataTableService.queryDataFieldLikeName(agentReq);
                                                Optional.ofNullable(agentDTOS).orElse(new ArrayList<>()).forEach(dto -> {
                                                    // 新增第三方平台加幅策略规则
                                                    long customId = SnowflakeIdWorker.nextId();
                                                    HotelProductChannelOnlineThirdPlatform channelOnlineThirdPlatform = new HotelProductChannelOnlineThirdPlatform();
                                                    channelOnlineThirdPlatform.setId(customId);
                                                    channelOnlineThirdPlatform.setIncreaseStrategyId(strategyId);
                                                    channelOnlineThirdPlatform.setPlatformId(dto.getId());
                                                    channelOnlineThirdPlatform.setPlatformName(dto.getFieldValue());
                                                    channelOnlineThirdPlatform.setCreateId(tokenUser.getId());
                                                    channelOnlineThirdPlatform.setModifiedId(tokenUser.getId());
                                                    channelOnlineThirdPlatform.setIsDeleted(0);
                                                    channelOnlineThirdPlatform.setGmtCreate(now);
                                                    channelOnlineThirdPlatform.setGmtModified(now);
                                                    hotelProductChannelOnlineThirdPlatformMapper.insert(channelOnlineThirdPlatform);
                                                    // 新增第三方平台加幅策略规则
                                                    HotelProductIncreaseStrategyRule agentRule = new HotelProductIncreaseStrategyRule();
                                                    agentRule.setId(SnowflakeIdWorker.nextId());
                                                    agentRule.setIncreaseStrategyId(strategyId);
                                                    // 加幅类型默认数值加0元
                                                    agentRule.setPriceType(1);
                                                    agentRule.setPrice(BigDecimal.ZERO);
                                                    // 可售类型默认不限制可售数
                                                    agentRule.setSaleableType(1);
                                                    agentRule.setCustomId(customId);
                                                    hotelProductIncreaseStrategyRuleMapper.insert(agentRule);
                                                });

                                                /**
                                                 * 设置加幅策略
                                                 */
                                                hotelProductStrategy = new HotelProductStrategy();
                                                hotelProductStrategy.setId(strategyId);
                                                hotelProductStrategy.setIncreaseStrategyName("默認策略");
                                                hotelProductStrategy.setSelfSalePermissionType(2);
                                                hotelProductStrategy.setAgentSalePermissionType(2);
                                                hotelProductStrategy.setHotelProductId(hotelProductId);
                                                hotelProductStrategy.setSelfSalePermissionId(offlineSelfRuleId);
                                                hotelProductStrategy.setAgentSalePermissionId(offlineAgentRuleId);
                                                hotelProductStrategy.setCreateId(tokenUser.getId());
                                                hotelProductStrategy.setIsDeleted(0);
                                                hotelProductStrategy.setGmtCreate(now);
                                                hotelProductStrategy.setGmtModified(now);
                                                hotelProductStrategyMapper.insert(hotelProductStrategy);

                                                /**
                                                 * 设置加幅策略有效期
                                                 */
                                                strategyDate = new HotelProductStrategyDate();
                                                strategyDate.setId(SnowflakeIdWorker.nextId());
                                                strategyDate.setIncreaseStrategyId(strategyId);
                                                strategyDate.setDateBegin(com.ctshk.common.utils.DateUtil.toLocalDate(DateUtil.toLocalDateTime(ratePlanSearchDTO.getDate())));
                                                strategyDate.setDateEnd(com.ctshk.common.utils.DateUtil.toLocalDate(DateUtil.toLocalDateTime(ratePlanSearchDTO.getDate()).plusDays(1)));
                                                strategyDate.setGmtCreate(now);
                                                strategyDate.setGmtModified(now);
                                                hotelProductStrategyDateMapper.insert(strategyDate);
                                            }
                                        }
                                    }
                                    /**
                                     * 设置成本价-90天内的 end
                                     */
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("API【龙腾捷旅】-方法【RoomSearch】解析失败,错误信息:[{}]", e.getMessage());
            return Result.failed(SystemError.HOTEL_API_10089);
        }

        return Result.success();
    }

    @Override
    public Result saveNTStaticInfo(String actionName, TokenUser user) {
        //先调用接口下载静态信息
        //downloadFile();
        return Result.success();
    }


    /**
     * 龙腾酒店下单校验
     * */
    @Override
    public Result<PreBookingCheckDTO> createOrderPre(NCNBHotelCreateOrderReq req) {
        log.info("进入[PreBookingCheck]酒店预下单");
        //hotelId对应hotelCode，在保存酒店的时候将龙腾hotelID保存为hotelCode,Room也是如此
        String pwd = SecureUtil.md5(password).toUpperCase();
        String param = "xmlRequest=<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<CNRequest>\n" +
                "  <!--用户信息-->\n" +
                "  <ActionName>PreBookingCheck</ActionName>\n" +
                "  <IdentityInfo>\n" +
                "    <AppId>" + appId + "</AppId>\n" +
                "    <SecurityKey>" + securityKey + "</SecurityKey>\n" +
                "    <UserName>" + username + "</UserName>\n" +
                "    <PassWord>" + pwd + "</PassWord>\n" +
                "    <Signature>" + Base64.encode(username+pwd+securityKey) + "</Signature>\n" +
                "  </IdentityInfo>\n" +
                "  <ScrollingInfo>\n" +
                "    <DisplayReq>30</DisplayReq>\n" +
                "    <PageItems>10</PageItems>\n" +
                "    <PageNo>1</PageNo>\n" +
                "  </ScrollingInfo>\n" +
                "  <!--查询条件-->\n" +
                "  <SearchConditions>\n" +
                "    <HotelId>"+req.getHotelId()+"</HotelId>\n" +
                "    <RoomId>"+req.getRoomId()+"</RoomId>\n" +
                "    <RateplanId>"+req.getRatePlanId()+"</RateplanId>\n" +
                "    <CheckIn>"+req.getCheckIn()+"</CheckIn>\n" +
                "    <CheckOut>"+req.getCheckOut()+"</CheckOut>\n" +
                "    <RoomCount>"+req.getRoomCount()+"</RoomCount>\n" +
                "    <Currency>"+req.getCurrency()+"</Currency>\n" +
                "    <OrderAmount>"+req.getOrderAmount()+"</OrderAmount>\n" +
                "  </SearchConditions>\n" +
                "</CNRequest>";
        String returnStr = HttpUtil.post(domain + ncnbUrl, param);
        JSONObject object = XML.toJSONObject(returnStr).getJSONObject("string").getJSONObject("content").getJSONObject("CNResponse");
        log.info("龙腾[PreBookingCheck]下单校验接口 response[{}]", object);
        int code = object.getJSONObject("MessageInfo").getInt("Code");
        if (code != 30000) {
            // 请求失败
            log.info("API【龙腾捷旅】-方法【PreBookingCheck】调用失败,错误信息:[{}]", object.getJSONObject("MessageInfo").get("Description"));
            throw new BusinessException(SystemError.HOTEL_API_10096);
        }
        OrderDTO orderDTO = JSONUtil.toBean(object, OrderDTO.class);
        PreBookingCheckDTO preBookingCheckDTO = new PreBookingCheckDTO();
        preBookingCheckDTO.setReturnCode(orderDTO.getData().getReturnCode());
        preBookingCheckDTO.setReturnMessage(orderDTO.getData().getReturnMessage());
        preBookingCheckDTO.setCount(orderDTO.getData().getPriceAndStatus().getPriceAndStatuCount());
        preBookingCheckDTO.setCurrency(orderDTO.getData().getPriceAndStatus().getPriceAndStatu().getCurrency());
        if(null != orderDTO.getData().getPriceAndStatus().getPriceAndStatu().getDate()){
            preBookingCheckDTO.setDate(orderDTO.getData().getPriceAndStatus().getPriceAndStatu().getDate().toString());
            preBookingCheckDTO.setLastCancelTime(orderDTO.getData().getPriceAndStatus().getPriceAndStatu().getLastCancelTime().toString());
        }
        preBookingCheckDTO.setPrice(orderDTO.getData().getPriceAndStatus().getPriceAndStatu().getPrice());
        preBookingCheckDTO.setStatu(orderDTO.getData().getPriceAndStatus().getPriceAndStatu().getStatu());
        return Result.success(preBookingCheckDTO);
    }


    /**
     * 龙腾酒店下单
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<BookingCheckDTO> createOrder(NCNBHotelCreateOrderReq req) {
        log.info("进入[Booking]酒店预定下单");
        BookingCheckDTO bookingCheckDTO = new BookingCheckDTO();
        Result<PreBookingCheckDTO> orderPre = createOrderPre(req);
        if(orderPre.getData().getReturnCode().equals("31001")){
            // 预定下单失败,返回api提示
            bookingCheckDTO = EntityUtil.copy(orderPre.getData(), BookingCheckDTO.class);
            return Result.success(bookingCheckDTO);
        }
        String bookPhone = "";
        if(StringUtils.isNotBlank(req.getBookPhone())){
            bookPhone=req.getBookPhone();
        }
        String guestPhone = "";
        if(StringUtils.isNotBlank(req.getGuestPhone())){
            guestPhone = req.getGuestPhone();
        }
        String guestFax = "";
        if(StringUtils.isNotBlank(req.getGuestFax())){
            guestFax = req.getGuestFax();
        }
        String cardTypeId = "";
        if(StringUtils.isNotBlank(req.getCardTypeId())){
            cardTypeId = req.getCardTypeId();
        }
        String cardNum = "";
        if(StringUtils.isNotBlank(cardNum)){
            cardNum = req.getCardNum();
        }
        String specialRemark = "";
        if(StringUtils.isNotBlank(req.getSpecialRemark())){
            specialRemark = req.getSpecialRemark();
        }
        String reserve1 = "";
        if(StringUtils.isNotBlank(req.getReserve1())) {
            reserve1 = req.getReserve1();
        }
        String reserve2 = "";
        if(StringUtils.isNotBlank(req.getReserve2())){
            reserve2 = req.getReserve2();
        }
        String pwd = SecureUtil.md5(password).toUpperCase();
        String param = "xmlRequest=<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<CNRequest>" +
                "  <!--用户信息-->" +
                "  <ActionName>Booking</ActionName>" +
                "  <IdentityInfo>" +
                "    <AppId>" + appId + "</AppId>" +
                "    <SecurityKey>" + securityKey + "</SecurityKey>" +
                "    <UserName>" + username + "</UserName>" +
                "    <PassWord>" + pwd + "</PassWord>" +
                "    <Signature>" + Base64.encode(username+pwd+securityKey) + "</Signature>" +
                "  </IdentityInfo>" +
                "  <ScrollingInfo>" +
                "    <DisplayReq>30</DisplayReq>" +
                "    <PageItems>4</PageItems>" +
                "    <PageNo>1</PageNo>" +
                "  </ScrollingInfo>" +
                "  <!--查询条件-->" +
                "  <SearchConditions>" +
                "    <HotelId>"+req.getHotelId()+"</HotelId>" +
                "    <RoomId>"+req.getRoomId()+"</RoomId>" +
                "    <RateplanId>"+req.getRatePlanId()+"</RateplanId>" +
                "    <CheckIn>"+req.getCheckIn()+"</CheckIn>" +
                "    <CheckOut>"+req.getCheckOut()+"</CheckOut>" +
                "    <RoomCount>"+req.getRoomCount()+"</RoomCount>" +
                "    <Currency>"+req.getCurrency()+"</Currency>" +
                "    <OrderAmount>"+req.getOrderAmount()+"</OrderAmount>" +
                "    <BookInfo>" +
                "      <BookName>"+req.getBookName()+"</BookName>" +
                "      <BookPhone>" +req.getBookPhone()+"</BookPhone>" +
                "    </BookInfo>" +
                "    <GuestInfo>" +
                "      <GuestName>"+req.getGuestName()+"</GuestName>" +
                "      <GuestPhone>" +guestPhone+"</GuestPhone>" +
                "      <GuestFax>" +req.getGuestFax()+"</GuestFax>" +
                "      <GuestType>" +req.getGuestType()+"</GuestType>" +
                "      <CardTypeId>" +cardTypeId+"</CardTypeId>" +
                "      <CardNum>" +cardNum+"</CardNum>" +
                "    </GuestInfo>" +
                "    <SpecialRemark>" +specialRemark+"</SpecialRemark>" +
                "    <Reserve>" +
                "      <Reserve1>" +reserve1+"</Reserve1>" +
                "      <Reserve2>" +reserve2+"</Reserve2>" +
                "    </Reserve>" +
                "    <CustomerOrderId>" +req.getCustomerOrderId()+"</CustomerOrderId>" +
                "  </SearchConditions>" +
                "</CNRequest>";
        log.info(param);
        // 设置10s超时
        String returnStr = HttpUtil.post(domain + ncnbUrl, param, 1000 * 10);
        JSONObject object = XML.toJSONObject(returnStr).getJSONObject("string").getJSONObject("content").getJSONObject("CNResponse");
        log.info("龙腾[Booking]下单接口 response[{}]", object);
        int code = object.getJSONObject("MessageInfo").getInt("Code");
        if (code != 30000) {
            // 请求失败
            log.info("API【龙腾捷旅】-接口【Booking】调用失败,错误信息:[{}]", object.getJSONObject("MessageInfo").get("Description"));
            throw new BusinessException(SystemError.HOTEL_API_10096);
        }
        OrderDTO orderDTO = JSONUtil.toBean(object, OrderDTO.class);
        bookingCheckDTO.setReturnCode(orderDTO.getData().getReturnCode());
        bookingCheckDTO.setReturnMessage(orderDTO.getData().getReturnMessage());
        bookingCheckDTO.setOrderId(orderDTO.getData().getOrder().getOrderId());
        bookingCheckDTO.setOrderStatusId(orderDTO.getData().getOrder().getOrderStatusId());
        bookingCheckDTO.setOrderStatus(orderDTO.getData().getOrder().getOrderStatus());
        return Result.success(bookingCheckDTO);
    }

    /**
     * 龙腾酒店城市列表查询
     * @return
     */
    @Override
    public List<CNHotelAreaDTO> queryHotelCityList() {
        log.info("进入酒店城市查询");
        String pwd = SecureUtil.md5(password).toUpperCase();
        String security = Base64.encode(username+pwd+securityKey);
        log.info("security[{}]",security);
        List<CNHotelAreaDTO> cnHotelAreaDTOS = new ArrayList<>();
        try {
            String auth = Base64.encode(username + pwd + securityKey + security);
            log.info("auth[{}]", auth);
            List<HotelCityDTO> hotelCityDTOList = GetApiUtils.downloadFile(domain + hotelCityUrl + auth);
            log.info("是否查询到城市信息[{}]", CollUtil.isNotEmpty(hotelCityDTOList));
            String countryId ="";
            String countryName ="";
            String provinceId ="";
            String provinceName ="";
            for (HotelCityDTO hotelCityDTO:hotelCityDTOList ) {
                if (null == hotelCityDTO || null == hotelCityDTO.getCityLevel()) {
                    continue;
                }
                if(hotelCityDTO.getCityLevel() == 1){
                    countryId=hotelCityDTO.getCityId();
                    countryName=hotelCityDTO.getCityName();
                    CNHotelAreaDTO cnHotelAreaDTO = new CNHotelAreaDTO();
                    cnHotelAreaDTO.setCountryId(countryId);
                    cnHotelAreaDTO.setCountryName(countryName);
                    cnHotelAreaDTO.setLevel(1);
                    cnHotelAreaDTOS.add(cnHotelAreaDTO);
                }
                if(hotelCityDTO.getCityLevel() == 2){
                    CNHotelAreaDTO cnHotelAreaDTO = new CNHotelAreaDTO();
                    provinceId=hotelCityDTO.getCityId();
                    provinceName=hotelCityDTO.getCityName();
                    cnHotelAreaDTO.setCountryId(countryId);
                    cnHotelAreaDTO.setCountryName(countryName);
                    cnHotelAreaDTO.setProvinceId(provinceId);
                    cnHotelAreaDTO.setProvinceName(provinceName);
                    cnHotelAreaDTO.setLevel(2);
                    cnHotelAreaDTOS.add(cnHotelAreaDTO);
                }
                if(hotelCityDTO.getCityLevel() == 3){
                    CNHotelAreaDTO cnHotelAreaDTO = new CNHotelAreaDTO();
                    cnHotelAreaDTO.setCountryId(countryId);
                    cnHotelAreaDTO.setCountryName(countryName);
                    cnHotelAreaDTO.setProvinceId(provinceId);
                    cnHotelAreaDTO.setProvinceName(provinceName);
                    cnHotelAreaDTO.setCityId(hotelCityDTO.getCityId());
                    cnHotelAreaDTO.setCityName(hotelCityDTO.getCityName());
                    cnHotelAreaDTO.setLevel(3);
                    cnHotelAreaDTOS.add(cnHotelAreaDTO);
                }
            }
        } catch (Exception e) {
            log.error("获取酒店城市失败[{}]",e);
            throw new BusinessException(SystemError.HOTEL_10043);
        }
        return cnHotelAreaDTOS;
    }

    @Override
    public List<AffiliatedGroup> queryAffiliatedGroup() {
        log.info("进入酒店品牌查询");
        String pwd = SecureUtil.md5(password).toUpperCase();
        String security = Base64.encode(username + pwd + securityKey);
        log.info("security[{}]",security);
        String returnStr = HttpUtil.get(domain + hotelAffiliatedGroupUrl + auth);
        log.info("龙腾酒店品牌查询接口 response解析前[{}]", returnStr);

        returnStr = HtmlUtil.unescape(HtmlUtil.unwrapHtmlTag(returnStr.replace("<!DOCTYPE html>", "").replace("静态参数查看", ""), "head", "title", "form", "link", "script", "meta", "input", "div", "pre", "body", "html", "Data")).replaceAll("\r|\n|\t", "").trim();

        log.info("龙腾酒店品牌查询接口 response解析后[{}]", returnStr);

        Document docResult= XmlUtil.parseXml(returnStr);
        Object code = XmlUtil.getByXPath("//CNResponse/MessageInfo/Code", docResult, XPathConstants.STRING);
        if ("30000".equals(code)) {
            return getCertainElementFromParentElement(docResult.getDocumentElement());
        }
        return Collections.emptyList();
    }

    @Override
    public List<RatePlanSearchDTO> queryRatePlanSearch(RatePlanSearchReq req) {
        String provinceId = "";
        String cityId = "";
        String hotelId = "";
        String roomId = "";
        String ratePlanId = "";
        String adultCount = "";
        String childCount = "";
        String childAges = "";
        String currency = "";
        String lang = "";
        String ratePlanOnly = "";
        if(StringUtils.isNotBlank(req.getProvinceId())){
            provinceId = req.getProvinceId();
        }
        if(StringUtils.isNotBlank(req.getCityId())) {
            cityId = req.getCityId();
        }
        if(StringUtils.isNotBlank(req.getHotelId())) {
            hotelId = req.getHotelId();
        }
        if(StringUtils.isNotBlank(req.getRoomId())) {
            roomId = req.getRoomId();
        }
        if(StringUtils.isNotBlank(req.getRatePlanId())){
            ratePlanId = req.getRatePlanId();
        }
        if(StringUtils.isNotBlank(req.getAdultCount())) {
            adultCount = req.getAdultCount();
        }
        if(StringUtils.isNotBlank(req.getChildCount())) {
            childCount = req.getChildCount();
        }
        if(StringUtils.isNotBlank(req.getChildAges())) {
            childAges = req.getChildAges();
        }
        if(StringUtils.isNotBlank(req.getCurrency())) {
            currency = req.getCurrency();
        }
        if(StringUtils.isNotBlank(req.getLang())) {
            lang = req.getLang();
        }
        if(StringUtils.isNotBlank(req.getRatePlanOnly())) {
            ratePlanOnly = req.getRatePlanOnly();
        }
        String pwd = SecureUtil.md5(password).toUpperCase();
        String param = "xmlRequest=<?xml version='1.0' encoding='utf-8'?>" +
                "<CNRequest>" +
                "  <!--用户信息-->" +
                "  <ActionName>RatePlanSearch</ActionName>" +
                "  <IdentityInfo>" +
                "    <AppId>" + appId + "</AppId>" +
                "    <SecurityKey>" + securityKey + "</SecurityKey>" +
                "    <UserName>" + username + "</UserName>" +
                "    <PassWord>" + pwd + "</PassWord>" +
                "    <Signature>" + Base64.encode(username+pwd+securityKey) + "</Signature>" +
                "  </IdentityInfo>" +
                "  <ScrollingInfo>" +
                "    <DisplayReq>40</DisplayReq>" +
                "    <PageItems>10</PageItems>" +
                "    <PageNo>1</PageNo>" +
                "  </ScrollingInfo>" +
                "  <!--查询条件-->" +
                "  <SearchConditions>" +
                "    <CountryId>"+req.getCountryId()+"</CountryId>" +
                "    <ProvinceId>" +provinceId+
                "    </ProvinceId>" +
                "    <CityId>" +cityId+
                "    </CityId>" +
                "    <HotelId>" +hotelId+
                "    </HotelId>" +
                "    <RoomId>" +roomId+
                "    </RoomId>" +
                "    <RatePlanId>" +ratePlanId+
                "    </RatePlanId>" +
                "    <StayDateRange>" +
                "      <CheckIn>"+req.getCheckIn()+"</CheckIn>" +
                "      <CheckOut>"+req.getCheckOut()+"</CheckOut>" +
                "    </StayDateRange>" +
                "    <GuestInfo>" +
                "      <AdultCount>" +adultCount+
                "      </AdultCount>" +
                "      <ChildCount>" +childCount+
                "      </ChildCount>" +
                "      <ChildAges>" +childAges+
                "      </ChildAges>" +
                "    </GuestInfo>" +
                "    <Currency>"+currency+"</Currency>" +
                "    <Lang>"+lang+"</Lang>" +
                "    <RatePlanOnly>"+ratePlanOnly+"</RatePlanOnly>" +
                "  </SearchConditions>" +
                "</CNRequest>";
        log.info(param);
        String returnStr = HttpUtil.post(domain + ncnbUrl, param);
        log.info(returnStr);
        JSONObject object = XML.toJSONObject(returnStr);
        JSONObject jsonObject = JSONUtil.parseFromXml(returnStr).getJSONObject("string").getJSONObject("content").getJSONObject("CNResponse");
        log.info("龙腾[RatePlanSearch]接口 response[{}]", jsonObject);
        RateDTO rateDTO = JSONUtil.toBean(jsonObject, RateDTO.class);
        Hotels hotels = rateDTO.getData().getHotels();
        String hotelCount = hotels.getHotelCount();
        List<RatePlanSearchDTO> ratePlanSearchDTOS = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(hotels.getHotel())){
            for (com.ctshk.rpc.hotel.dto.rate.Hotel hotel:hotels.getHotel() ) {
                String hotelId1 = hotel.getHotelId();
                String hotelName = hotel.getHotelName();
                if(null != hotel.getRooms()) {
                    String roomCount = hotel.getRooms().getRoomCount();
                    if(CollectionUtils.isNotEmpty(hotel.getRooms().getRoom())){
                        List<Room> roomList = hotel.getRooms().getRoom();
                        for (Room room:roomList) {
                            String roomName = room.getRoomName();
                            String roomId1 = room.getRoomId();
                            String rateCount = room.getRates().getRateCount();
                            RatePlan ratePlan = null;
                            if(CollectionUtils.isNotEmpty(room.getRatePlans().getRatePlan())){
                                ratePlan = room.getRatePlans().getRatePlan().get(0);
                            }
                            Rate rate =null;
                            if(CollectionUtils.isNotEmpty(room.getRates().getRate())){
                                rate = room.getRates().getRate().get(0);
                            }
                            if(rate != null){
                                List<PriceAndStatu> priceAndStatuList = rate.getPriceAndStatus().getPriceAndStatu();
                                if(CollectionUtils.isNotEmpty(priceAndStatuList)){
                                    for (PriceAndStatu priceAndStatu:priceAndStatuList ) {
                                        RatePlanSearchDTO ratePlanSearchDTO = new RatePlanSearchDTO();
                                        ratePlanSearchDTO.setHotelId(hotelId1);
                                        ratePlanSearchDTO.setHotelName(hotelName);
                                        ratePlanSearchDTO.setRoomCount(roomCount);
                                        ratePlanSearchDTO.setRoomId(roomId1);
                                        ratePlanSearchDTO.setRoomName(roomName);
                                        ratePlanSearchDTO.setRatePlanCount(ratePlan.getMinRoomCount());
                                        ratePlanSearchDTO.setRatePlanId(ratePlan.getRatePlanId());
                                        ratePlanSearchDTO.setRatePlanName(ratePlan.getRatePlanName());
                                        ratePlanSearchDTO.setCutOffDay(Integer.parseInt(ratePlan.getMinDay()));
                                        ratePlanSearchDTO.setCutOffTime(ratePlan.getCutOffTime());
                                        ratePlanSearchDTO.setBreakfast(ratePlan.getBreakfast());
                                        ratePlanSearchDTO.setBreakfastType(ratePlan.getBreakfastType());
                                        ratePlanSearchDTO.setMinRoomCount(Integer.parseInt(ratePlan.getMinRoomCount()));
                                        ratePlanSearchDTO.setPersonCount(Integer.parseInt(ratePlan.getPersonCount()));
                                        ratePlanSearchDTO.setMinDay(Integer.parseInt(ratePlan.getMinDay()));
                                        ratePlanSearchDTO.setBedLimit(ratePlan.getBedLimit());
                                        ratePlanSearchDTO.setNationality(ratePlan.getNationality());
                                        ratePlanSearchDTO.setDescription(ratePlan.getDescription());
                                        ratePlanSearchDTO.setRateId(priceAndStatu.getRateId());
                                        ratePlanSearchDTO.setDate(priceAndStatu.getDate());
                                        ratePlanSearchDTO.setPrice(priceAndStatu.getPrice());
                                        ratePlanSearchDTO.setCurrency(priceAndStatu.getCurrency());
                                        ratePlanSearchDTO.setCount(Integer.parseInt(priceAndStatu.getCount()));
                                        ratePlanSearchDTO.setStatu(Integer.parseInt(priceAndStatu.getStatu()));
                                        ratePlanSearchDTO.setLastCancelTime(priceAndStatu.getLastCancelTime());
                                        ratePlanSearchDTOS.add(ratePlanSearchDTO);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        log.info("======>>>>"+ratePlanSearchDTOS);
        return ratePlanSearchDTOS;
    }

    @Override
    public Result<BookingCheckDTO> bookingCancel(String orderId, TokenUser currentUser) {
        String pwd = SecureUtil.md5(password).toUpperCase();
        String param = "xmlRequest=<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<CNRequest>\n" +
                "  <!--用户信息-->\n" +
                "  <ActionName>BookingCancel</ActionName>\n" +
                "  <IdentityInfo>\n" +
                "    <AppId>" + appId + "</AppId>\n" +
                "    <SecurityKey>" + securityKey + "</SecurityKey>\n" +
                "    <UserName>" + username + "</UserName>\n" +
                "    <PassWord>" + pwd + "</PassWord>\n" +
                "    <Signature>" + Base64.encode(username+pwd+securityKey) + "</Signature>\n" +
                "  </IdentityInfo>\n" +
                "  <ScrollingInfo>\n" +
                "    <DisplayReq>30</DisplayReq>\n" +
                "    <PageItems>\n" +
                "      4\n" +
                "    </PageItems>\n" +
                "    <PageNo>1</PageNo>\n" +
                "  </ScrollingInfo>\n" +
                "  <!--查询条件-->\n" +
                "  <SearchConditions>\n" +
                "    <OrderId>"+orderId+"</OrderId>\n" +
                "  </SearchConditions>\n" +
                "</CNRequest>";
        String returnStr = HttpUtil.post(domain + ncnbUrl, param);
        log.info(returnStr);
        JSONObject object = XML.toJSONObject(returnStr);
        JSONObject jsonObject = JSONUtil.parseFromXml(returnStr).getJSONObject("string").getJSONObject("content").getJSONObject("CNResponse");
        OrderDTO orderDTO = JSONUtil.toBean(jsonObject, OrderDTO.class);
        BookingCheckDTO bookingCheckDTO = new BookingCheckDTO();
        bookingCheckDTO.setReturnCode(orderDTO.getData().getReturnCode());
        bookingCheckDTO.setReturnMessage(orderDTO.getData().getReturnMessage());
        if(null != orderDTO.getData().getOrder()){
            bookingCheckDTO.setOrderId(orderDTO.getData().getOrder().getOrderId());
            bookingCheckDTO.setOrderStatusId(orderDTO.getData().getOrder().getOrderStatusId());
            bookingCheckDTO.setOrderStatus(orderDTO.getData().getOrder().getOrderStatus());
        }
        return Result.success(bookingCheckDTO);
    }

    public static String getStarLevelFunc(String starCode){
        String starLevel = null;
        if(starCode.equals("012009")){//这些数据来源于龙腾接口文档里的参照数据
            starLevel="1";
        }else if(starCode.equals("012011")){
            starLevel="1";
        }else if(starCode.equals("012012")){
            starLevel="2";
        }else if(starCode.equals("012013")){
            starLevel="3";
        }else if(starCode.equals("012014")){
            starLevel="3";
        }else if(starCode.equals("012015")){
            starLevel="4";
        }else if(starCode.equals("012016")){
            starLevel="4";
        }else if(starCode.equals("012017")){
            starLevel="5";
        }else if(starCode.equals("012018")){
            starLevel="5";
        }else if(starCode.equals("012019")){
            starLevel="7";
        }else if(starCode.equals("012020")){
            starLevel="7";
        }
        return starLevel;
    }

    /**
     * 解析酒店城市静态html
     * @param ele
     * @return
     */
    private static List<AffiliatedGroup> getCertainElementFromParentElement(Element ele) {
        // 根据标签名称获取标签元素列表
        NodeList propertyEleList = ele.getElementsByTagName("AffiliatedGroup");
        List<AffiliatedGroup> list = new ArrayList<>();
        AffiliatedGroup affiliatedGroup = null;
        for (int i = 0; i < propertyEleList.getLength(); i++) {
            Node node = propertyEleList.item(i);
            if (node instanceof Element) {
                affiliatedGroup = new AffiliatedGroup();
                Element propertyEle = (Element) node;
                String id = propertyEle.getAttribute("AffiliatedGroupId");
                if (StringUtils.isBlank(id)) {
                    continue;
                }
                String name = propertyEle.getAttribute("AffiliatedGroupName");
                affiliatedGroup.setAffiliatedGroupId(id);
                affiliatedGroup.setAffiliatedGroupName(name);
                list.add(affiliatedGroup);
            }
        }
        return list;
    }

}

/*
*
* //删除所有之前的数据
        QueryWrapper<HotelStaticCity> queryWrapperCity = new QueryWrapper<>();
        queryWrapperCity.lambda().eq(HotelStaticCity::getIsDeleted,IsDeletedCode.NO.getCode());

        QueryWrapper<HotelStaticProvience> queryWrapperProvience = new QueryWrapper<>();
        queryWrapperProvience.lambda().eq(HotelStaticProvience::getIsDeleted,IsDeletedCode.NO.getCode());

        QueryWrapper<HotelStaticCountry> queryWrapperCountry = new QueryWrapper<>();
        queryWrapperCountry.lambda().eq(HotelStaticCountry::getIsDeleted,IsDeletedCode.NO.getCode());

        List<HotelStaticCity> hotelStaticCities = hotelStaticCityMapper.selectList(queryWrapperCity);
        for (int i = 0; i <hotelStaticCities.size(); i++) {
            Long id = hotelStaticCities.get(i).getId();
            hotelStaticCityMapper.deleteById(id);
        }
        List<HotelStaticProvience> hotelStaticProvience = hotelStaticProvienceMapper.selectList(queryWrapperProvience);
        for (int i = 0; i <hotelStaticProvience.size() ; i++) {
            Long id = hotelStaticProvience.get(i).getId();
            hotelStaticProvienceMapper.deleteById(id);
        }
        List<HotelStaticCountry> hotelStaticCountry = hotelStaticCountryMapper.selectList(queryWrapperCountry);
        for (int i = 0; i <hotelStaticCountry.size() ; i++) {
            Long id = hotelStaticCountry.get(i).getId();
            hotelStaticCountryMapper.deleteById(id);
        }
*
* */